package com.googlecode.chios.jnet.worker;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import com.googlecode.chios.jnet.handler.Task;
import com.googlecode.chios.jnet.io.AioSession;


/**
 * 
 * 业务处理线程
 * 处理写, 读操作(解析byteBuffer)
 * @author luzj
 */
public class AioWorker implements Runnable {

	private final BlockingQueue<Task> taskQueue = new LinkedTransferQueue<Task>();
	
	private final int id;
	
	private final Executor executor;
	
	private final AtomicBoolean wakenUp = new AtomicBoolean(false);
	
	public AioWorker(int id, Executor executor) {
		this.id = id;
		this.executor = executor;
	}

	public void registerSession(AioSession session) {
		if(session.isOpen() && (!wakenUp.getAndSet(true))) {
			WorkerContext.startWorker(executor, this);
		}
	}
	
	public boolean offerTask(Task task) {
		return taskQueue.offer(task);
	}

	@Override
	public void run() {
		for(;;) {
			try {
				Task task = taskQueue.take();
				if(task != null) {
					task.run();
				}
			} catch (InterruptedException e) {
				//ignore
			}
		}
	}

	@Override
	public String toString() {
		return "AioWorker [id=" + id + "]";
	}
	
}
